package com.yiyi.credit.manage.abutment.service;

import com.github.pagehelper.PageHelper;
import com.yiyi.credit.manage.abutment.common.enums.ResponseCode;
import com.yiyi.credit.manage.abutment.common.exceptions.ServiceException;
import com.yiyi.credit.manage.abutment.mapper.SubProductMapper;
import com.yiyi.credit.manage.abutment.mapper.SubStationMapper;
import com.yiyi.credit.manage.model.entity.SubProduct;
import com.yiyi.credit.manage.model.entity.SubStation;
import com.yiyi.credit.manage.model.po.SubstationTradePO;
import com.yiyi.credit.manage.model.vo.SubstationTradeVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class SubStationService {
    private static final Logger logger = LoggerFactory.getLogger(SubStationService.class);

    @Autowired
    private SubStationMapper subStationMapper;
    @Autowired
    private SubProductMapper subProductMapper;


    public List<SubStation> getSubStationList() throws ServiceException {
        Example example = new Example(SubStation.class);
        return subStationMapper.selectByExample(example);
    }

    public List<SubStation> findSubstationByIds(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids))
            return Collections.emptyList();

        Example example = new Example(SubStation.class);
        example.createCriteria().andIn("id", ids);
        return subStationMapper.selectByExample(example);
    }


    public List<SubStation> getSubStationPageList(SubStation subStation) throws ServiceException {
        return subStationMapper.getSubStationPageList(subStation);
    }


    public int addSubStation(SubStation subStation) throws ServiceException {
        List<SubStation> list = getSubStationByName(subStation.getSubStationName());
        if (null != list && list.size() > 0) {
            throw new ServiceException(ResponseCode.SUB_STATION_EXIST);
        }

        subStation.setCreateTime(new Date().getTime());
        subStation.setUpdateTime(new Date().getTime());
        return subStationMapper.insertSelective(subStation);
    }


    public int updateSubStation(SubStation subStation) throws ServiceException {

        SubStation checkSubStation = subStationMapper.selectByPrimaryKey(subStation.getId());
        if (checkSubStation == null) {
            throw new ServiceException(ResponseCode.SUB_STATION_NO_EXIST);
        }
        subStation.setUpdateTime(new Date().getTime());
        return subStationMapper.updateByPrimaryKeySelective(subStation);
    }


    public int deleteSubStation(SubStation subStation) throws ServiceException {

        SubStation checksubStation = getSubStationById(subStation.getId());
        if (checksubStation == null) {
            throw new ServiceException(ResponseCode.SERVICE_ERR);
        }
        return subStationMapper.deleteByPrimaryKey(subStation);
    }


    public int changeSubStationStatus(SubStation subStation) throws ServiceException {

        SubStation checksubStation = getSubStationById(subStation.getId());
        if (checksubStation == null) {
            throw new ServiceException(ResponseCode.SERVICE_ERR);
        }
        checksubStation.setStatus(subStation.getStatus());
        return subStationMapper.updateByPrimaryKeySelective(checksubStation);
    }


    public List<SubStation> getSubStationByName(String subStationName) throws ServiceException {

        Example example = new Example(SubStation.class);
        example.createCriteria().andEqualTo("subStationName", subStationName);
        return subStationMapper.selectByExample(example);
    }


    public SubStation getSubStationById(Long id) throws ServiceException {

        return subStationMapper.selectByPrimaryKey(id);
    }


    public List<SubStation> getSubStationByIds(String ids) throws ServiceException {

        String[] checkIds = ids.split(",");
        List<SubStation> result = new ArrayList<>();
        for (int i = 0; i < checkIds.length; i++) {
            Long subStationId = Long.parseLong(checkIds[i]);
            SubStation subStation = subStationMapper.selectByPrimaryKey(subStationId);
            result.add(subStation);
        }
        return result;
    }


    public int checkSubStationNo(String subStationNo) throws ServiceException {
        Example example = new Example(SubStation.class);
        example.createCriteria().andEqualTo("subStationNo", subStationNo);
        return subStationMapper.selectByExample(example).size();
    }

    public Map<Long, SubStation> findByIds(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids))
            return Collections.emptyMap();

        Example stationMapper = new Example(SubStation.class);
        stationMapper.createCriteria().andIn("id", ids);
        return subStationMapper.selectByExample(stationMapper)
                .stream()
                .collect(Collectors.toMap(SubStation::getId, s -> s));
    }

    public Map<String, SubProduct> findSubProductByIds(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids))
            return Collections.emptyMap();

        Example products = new Example(SubProduct.class);
        products.createCriteria().andIn("id", ids);
        return subProductMapper.selectByExample(products)
                .stream()
                .collect(Collectors.toMap(SubProduct::getId, s -> s));
    }

    public List<SubstationTradeVO> listTrades(SubstationTradePO tradePO) {
        PageHelper.startPage(tradePO.getPageIndex(), tradePO.getPageSize());
        List<SubstationTradeVO> list = subStationMapper.listTrades(tradePO);
        Set<Long> substationIds = new HashSet<>();
        Set<Long> subProducts = new HashSet<>();
        list.forEach(vo -> {
            substationIds.add(vo.getSubstationId());
            subProducts.add(vo.getSubProductId());
            if (com.yiyi.credit.manage.abutment.common.enums.ProductType.COMMON_PRODUCT.getKey() == Integer.valueOf(vo.getProjectType())) {
                vo.setProjectStatus(vo.getsStatus());
            } else {
                vo.setProjectStatus(vo.getmStatus());
            }

        });

        Map<String, SubProduct> products = findSubProductByIds(subProducts);
        Map<Long, SubStation> stations = findByIds(substationIds);

        list.forEach(vo -> {
            SubProduct sp = products.get(vo.getSubProductId());
            SubStation ss = stations.get(vo.getSubstationId());
            vo.setSubstationName(ss == null ? "" : ss.getSubStationName());
            if (sp != null) {
                vo.setSubProductName(sp.getProductName());
                vo.setClosePeriod(sp.getClosedPeriod());
                vo.setClosePeriodUnit(sp.getClosedPeriodUnit());
            }
        });

        return list;
    }
}
